<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\lists\card;


use app\adminapi\lists\BaseAdminDataLists;
use app\common\lists\ListsExcelInterface;
use app\common\model\card\Card;
use app\common\lists\ListsSearchInterface;
use app\common\model\card\CardGroup;
use app\common\model\card\CardTag;
use app\common\model\user\User;

/**
 * card列表
 * Class CardLists
 * @package app\adminapi\listscard
 */
class CardLists extends BaseAdminDataLists implements ListsSearchInterface,ListsExcelInterface
{


    /**
     * @notes 设置搜索条件
     * @return \string[][]
     * @author gzx
     * @date 2025/04/11 13:48
     */
    public function setSearch(): array
    {
        return [
            '=' => ['card_id', 'c.card_bin', 'user_pid', 'user_id', 'group_id', 'tag_ids', 'status'],
            '%like' => ['alias', 'card_no'],
        ];
    }

    /**
     * @notes 搜索条件
     * @date 2023/2/24 15:26
     */
    public function queryWhere()
    {
        $where = [];


        if (!empty($this->params['start_time'])) {
            $where[] = ['c.create_time', '>=', strtotime($this->params['start_time'])];
        }

        if (!empty($this->params['end_time'])) {
            $where[] = ['c.create_time', '<=', strtotime($this->params['end_time'])];
        }

        return $where;
    }

    /**
     * @notes 获取card列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author gzx
     * @date 2025/04/11 13:48
     */
    public function lists(): array
    {
        //接口排序
        $order = ['c.spend_money' => 'desc'];
        if (!empty($this->params['sort_field'])) {
            $sortOrder = strtolower($this->params['sort_order'] ?? '') === 'asc' ? 'asc' : 'desc';
            if ($this->params['sort_field'] == 'spend_money') {
                $order = ['c.spend_money' => $sortOrder];
            } else {
                $order = ['c.id' => $sortOrder];
            }
        }

        $list =  Card::alias('c')
            ->leftJoin('sc_user_group ug', 'c.group_id = ug.id')
            ->where($this->searchWhere)
            ->where($this->queryWhere())
            ->whereNotNull('user_id') //只查询已分配运营者的卡片
            ->field(['c.id', 'c.card_id', 'c.card_no', 'c.card_bin', 'c.user_pid', 'c.user_id', 'c.available_balance', 'c.alias', 'c.secure_msg', 'c.group_id','c.card_group_id', 'c.tag_ids', 'c.single_transaction_limit',
                'c.daily_transaction_limit','c.monthly_transaction_limit', 'c.total_transaction_limit', 'c.status', 'c.remark', 'c.extra', 'c.latest_time', 'c.transaction_status', 'c.billing_amount', 'c.create_time', 'c.spend_money', 'c.limit_money', 'ug.company_name'])
            ->limit($this->limitOffset, $this->limitLength)
            ->order($order)
            ->select()
            ->toArray();
        $cardGroup = CardGroup::column('name', 'id');
        $cardTag = CardTag::column('name', 'id');
        $users = User::column('account', 'id');

        foreach ($list as &$item) {
            //这里处理敏感信息
            $item['card_no'] = '********'.substr($item['card_no'], -4);
            if (isset($_GET['export'])) {
                $secure = decrypt($item['secure_msg']);
                $secure = json_decode($secure, true);
                $item['card_no'] = $secure['card_num'] ?? '';
                $item['cvv'] = $secure['cvv'] ?? '';
                $item['expiredMonth'] = $secure['expiry_month'] ?? '';
                $item['expiredYear'] = $secure['expiry_year'] ?? '';
            }
            $item['account'] =$users[$item['user_id']];
            $item['secure_msg'] = '...';
            $item['card_group_name'] = $cardGroup[$item['card_group_id']] ?? '';
            $item['card_tag_name'] = '';

            foreach (explode(',', $item['tag_ids']??'') as $tag) {
                $item['card_tag_name'] = $item['card_tag_name'] . ($cardTag[$tag] ?? '未知标签') . ',';
            }
            $item['card_tag_name'] = rtrim($item['card_tag_name'], ',');
            $item['company_name'] = $item['company_name'] ?? '';
            $item['create_time'] = is_numeric($item['create_time']) ? date('Y-m-d H:i:s', $item['create_time']) : $item['create_time'];

            //通过卡号后4位查询的进行更新交易记录实时api查询,只有输入卡号后4位才更新api，太多记录会超时
            if (isset($_GET['card_no']) && strlen($_GET['card_no']) == 4) {
                $update = update_card_detail($item['card_id']);
                $item = array_merge($item, $update);
            }
        }

        return $list;
    }


    /**
     * @notes 获取card数量
     * @return int
     * @author gzx
     * @date 2025/04/11 13:48
     */
    public function count(): int
    {
        return Card::alias('c')->where($this->searchWhere)
            ->where($this->queryWhere())->count();
    }

    /**
     * @notes 导出文件名
     * @return string
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setFileName(): string
    {
        return '卡片列表';
    }


    /**
     * @notes 导出字段
     * @date 2022/11/24 16:17
     */
    public function setExcelFields(): array
    {
        return [
            'card_id' => 'card_ID',
            'card_no' => 'card_no',
            'alias' => '别名',
            'card_group_name' => '卡组名称',
            'card_tag_name' => '标签',
            'account' => '运营者',
            'cvv' => 'cvv',
            'expiredMonth' => 'expired_month',
            'expiredYear' => 'expired_year',
            'company_name' => '公司名称',
            'create_time' => '创建时间',
        ];
    }

}